//
//  UIView+YYClick.m
//  ocdemo
//
//  Created by JieNing.Zhang on 2023/4/4.
//  Copyright © 2023 zjn. All rights reserved.
//
#import "UIView+YYClick.h"
//#import "UIImage+ERCategory.h"

#import <objc/runtime.h>
//#import <Masonry.h>

static char *YYUIViewClickKey;
static char *YYUIViewClickTMKey;

static char *YYUIViewFlagInfoKey;


@implementation UIView (YYClick)

- (void)removeAllSubviews {
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
}

- (void)YYViewClick:(UIViewClickBlock)handle {
    self.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_viewClick)];
    [self addGestureRecognizer:tap];
    objc_setAssociatedObject(self, &YYUIViewClickKey, handle, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

/**
 *  如果当前还没有额外添加点击事件，增加UIView的点击事件
 */
-(void)YYViewClickIfNoneHandle:(UIViewClickBlock)handle{
    UIViewClickBlock callBack = objc_getAssociatedObject(self, &YYUIViewClickKey);
    if (callBack) {
    } else {
        [self YYViewClick:handle];
    }
}

- (void)_viewClick {
    UIViewClickBlock callBack = objc_getAssociatedObject(self, &YYUIViewClickKey);
    if (callBack!= nil){
        
        // 通过 flagInfo 中的 时间戳，防止 短时间内 重复点击
        double lastClickTM = self.clickTMInMs;
        double nowTM = [[NSDate date] timeIntervalSince1970]*1000;
        if (lastClickTM > 0) {
            if (nowTM < lastClickTM+1000) {
                // 短时间内（1000ms） 重复点击
                return;
            }
        }
        
        self.clickTMInMs = nowTM;
        
        callBack(self);
    }
}

- (void)setClickTMInMs:(double)tsInMs {
    objc_setAssociatedObject(self, &YYUIViewClickTMKey, @(tsInMs), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (double)clickTMInMs {
    id tsNum = objc_getAssociatedObject(self, &YYUIViewClickTMKey);
    if ([tsNum isKindOfClass:[NSNumber class]]) {
        return ((NSNumber *)tsNum).doubleValue;
    }
    return 0;
}


- (void)setFlagInfo:(NSDictionary *)flagInfo {
    if ([flagInfo isKindOfClass:[NSDictionary class]]) {
        objc_setAssociatedObject(self, &YYUIViewFlagInfoKey, flagInfo, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    } else {
        objc_setAssociatedObject(self, &YYUIViewFlagInfoKey, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
}

- (NSDictionary *)flagInfo {
    id rtnDic = objc_getAssociatedObject(self, &YYUIViewFlagInfoKey);
    if ([rtnDic isKindOfClass:[NSDictionary class]]) {
        return (NSDictionary *)rtnDic;
    }
    return nil;
}

- (UIImage*)createImageWithScale:(CGFloat)scale rect:(CGRect)rect {
    if (CGRectEqualToRect(rect, CGRectZero)) {
        rect = self.bounds;
    }
    
    // https://www.jianshu.com/p/6ae339a38b79
    
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, YES, scale);  //NO，YES 控制是否透明
    if ([self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)]) {
        [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
    } else {
        [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    }
    UIImage *wholeImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // 如果 frame 和 bounds 一样，只要返回 wholeImage 就好。
    if (CGRectEqualToRect(rect, self.bounds)) {
        return wholeImage;
    }
    
    if(0 == scale) {
        scale = [[UIScreen mainScreen] scale];
    }
    
    CGRect imageToExtractFrame = CGRectApplyAffineTransform(rect, CGAffineTransformMakeScale(scale, scale));
    CGImageRef imageRef = CGImageCreateWithImageInRect([wholeImage CGImage], imageToExtractFrame);
    
    wholeImage = nil;
    
    UIImage *image = [UIImage imageWithCGImage:imageRef
                                         scale:scale
                                   orientation:UIImageOrientationUp];
    CGImageRelease(imageRef);
    return image;
}

- (UIImage*)createImageWithScale:(CGFloat)scale
{
    return [self createImageWithScale:scale rect:CGRectZero];
}


// 为当前view 添加一个热区，热区跟随当前view中心点移动，保留 通过 YYViewClick 添加的 点击事件
-(UIView*)addHotAreaWithSameYYViewClick:(CGSize)hotAreaSize {
//    if (self.superview) {
//        UIView *hotArea = [[UIView alloc]initWithFrame:CGRectMake(0, 0, hotAreaSize.width, hotAreaSize.height)];
//        [self.superview insertSubview:hotArea belowSubview:self];
//        
//        [hotArea mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.width.mas_equalTo(hotAreaSize.width);
//            make.height.mas_equalTo(hotAreaSize.height);
//            make.center.equalTo(self);
//        }];
//        
//        UIViewClickBlock callBack = objc_getAssociatedObject(self, &YYUIViewClickKey);
//        if (callBack!= nil) {
//            hotArea.userInteractionEnabled = YES;
//            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:hotArea action:@selector(_viewClick)];
//            [hotArea addGestureRecognizer:tap];
//            objc_setAssociatedObject(hotArea, &YYUIViewClickKey, callBack, OBJC_ASSOCIATION_COPY_NONATOMIC);
//        }
//        
//        return hotArea;
//        
//    }
    return nil;
}


// 切圆角函数
-(CGPathRef)makeCornerMaskPath:(NSArray<NSNumber *> *)cornerRadiusArr {
    const CGFloat minX = 0;//CGRectGetMinX(self.bounds);
    const CGFloat minY = 0;//CGRectGetMinY(self.bounds);
    const CGFloat maxX = CGRectGetMaxX(self.bounds);
    const CGFloat maxY = CGRectGetMaxY(self.bounds);
    
    CGFloat crTopLeft = cornerRadiusArr.count > 0 ? cornerRadiusArr[0].floatValue : 0.f;
    CGFloat crTopRight= cornerRadiusArr.count > 1 ? cornerRadiusArr[1].floatValue : 0.f;
    CGFloat crBottomLeft = cornerRadiusArr.count > 2 ? cornerRadiusArr[2].floatValue : 0.f;
    CGFloat crBottomRight = cornerRadiusArr.count > 3 ? cornerRadiusArr[3].floatValue : 0.f;
    
    // 逆时针 组装4个角的path
    CGMutablePathRef path = CGPathCreateMutable();
    // 顶 左
    if (crTopLeft > 0.f) {
        const CGFloat topLeftCenterX = minX + crTopLeft;
        const CGFloat topLeftCenterY = minY + crTopLeft;
        
        //If the specified path already contains a subpath, Core Graphics implicitly adds a line connecting the subpath’s current point to the beginning of the arc.
        //If the path is empty, Core Graphics creates a new subpath with a starting point set to the starting point of the arc.
        //The ending point of the arc becomes the new current point of the path.
        CGPathAddArc(path, NULL, topLeftCenterX, topLeftCenterY, crTopLeft, M_PI, 3 * M_PI_2, NO);
    } else {
        CGPathMoveToPoint(path, NULL, minX, minY);
        //CGPathAddLineToPoint(path, NULL, 0, 0);
    }
    
    // 顶 右
    if (crTopRight > 0.f) {
        const CGFloat topRightCenterX = maxX - crTopRight;
        const CGFloat topRightCenterY = minY + crTopRight;
        CGPathAddArc(path, NULL, topRightCenterX, topRightCenterY, crTopRight, 3 * M_PI_2, 0, NO);
    } else {
        CGPathAddLineToPoint(path, NULL, maxX, minY);
    }
    
    // 底 右
    if (crBottomRight > 0.f) {
        const CGFloat bottomRightCenterX = maxX - crBottomRight;
        const CGFloat bottomRightCenterY = maxY - crBottomRight;
        CGPathAddArc(path, NULL, bottomRightCenterX, bottomRightCenterY, crBottomRight, 0, M_PI_2, NO);
    } else {
        CGPathAddLineToPoint(path, NULL, maxX, maxY);
    }
    
    // 底 左
    if (crBottomLeft > 0.f) {
        const CGFloat bottomLeftCenterX = minX + crBottomLeft;
        const CGFloat bottomLeftCenterY = maxY - crBottomLeft;
        CGPathAddArc(path, NULL, bottomLeftCenterX, bottomLeftCenterY, crBottomLeft, M_PI_2,M_PI, NO);
    } else {
        CGPathAddLineToPoint(path, NULL, minX, maxY);
    }
    
    
    CGPathCloseSubpath(path);
    return path;
}

// 通过加入遮罩，切出圆角
// 圆角半径从 cornerRadiusArr 中取，0:左上, 1:右上, 2:左下, 3:右下
-(void)makeCornerMaskLayer:(NSArray<NSNumber *> *)cornerRadiusArr {
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = [self makeCornerMaskPath:cornerRadiusArr];
    self.layer.mask = maskLayer;
}

-(UIViewController *)nearestVC {
    UIResponder* nextResponder = self;
    do {
        nextResponder = [nextResponder nextResponder];
        if ([nextResponder isKindOfClass:UIViewController.class]) {
            return (UIViewController *)nextResponder;
        }
    } while (nextResponder != nil);
    return nil;
}

- (void)loop2RemoveAllConstraints {
    UIView *superview = self.superview;
    while (superview != nil) {
        for (NSLayoutConstraint *c in superview.constraints) {
            if (c.firstItem == self || c.secondItem == self) {
                [superview removeConstraint:c];
            }
        }
        superview = superview.superview;
    }

    [self removeConstraints:self.constraints];
    self.translatesAutoresizingMaskIntoConstraints = YES;
}

//- (UIImageView *)myBlurEffectViewAdaptDark:(CGRect)rect {
//    UIImageView *backView = [[UIImageView alloc]initWithFrame:rect];
//    backView.image = [UIImage imageWithColor:[UIColor colorWithHexString:@"#1A1A1A" alpha:0.2]
//                                        size:CGSizeMake(rect.size.width, rect.size.height)];
//    
//    BOOL isDark = (self.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark);
//    
//    UIBlurEffect *effect = [UIBlurEffect effectWithStyle: (isDark ? UIBlurEffectStyleDark : UIBlurEffectStyleLight)];
//    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
//    effectView.frame = CGRectMake(0, 0, rect.size.width, rect.size.height);
//    [backView addSubview:effectView];
//    
//    return backView;
//}

@end
